import com.google.gson.Gson;
import meta.MetaEachFileInfo;
import meta.MetaFolderInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class Folder2JsonLogic {

    private MetaFolderInfo metaFolderInfo;
    private File mRootFolder;

    public void execute(String _needScanFolderPath, String _jsonOutputPath) {

        mRootFolder = new File(_needScanFolderPath);
        if (mRootFolder.isDirectory()) {

            metaFolderInfo = new MetaFolderInfo();
            metaFolderInfo.rootFolderName = mRootFolder.getName();
            metaFolderInfo.allFileInfoList = new ArrayList<>();

            doScanEachFileUnderFolder(mRootFolder);
            Gson gson = new Gson();
            writeStringToFile(gson.toJson(metaFolderInfo), _jsonOutputPath);
            System.out.println("Write file to : " + _jsonOutputPath);

        } else {
            System.out.println("");
            System.out.println("ERROR:: path : " + _needScanFolderPath + " is not an folder");
        }
    }

    private void doScanEachFileUnderFolder(File _folder) {
        for (File subFile : _folder.listFiles()) {
            if (subFile.isDirectory()) {
                doScanEachFileUnderFolder(subFile);
            } else {
                MetaEachFileInfo eachFileInfo = new MetaEachFileInfo();
                eachFileInfo.name = subFile.getName();
                eachFileInfo.size = subFile.length();
                eachFileInfo.path = mRootFolder.getName() + "/" + subFile.getAbsolutePath().substring(mRootFolder.getAbsolutePath().length() + 1);
                eachFileInfo.path = eachFileInfo.path.replaceAll("\\\\", "/");
                metaFolderInfo.allFileInfoList.add(eachFileInfo);
            }
        }
    }

    private void writeStringToFile(String _str, String _filePath) {
        try {
            File f = new File(_filePath);
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();
            OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(f, true), "UTF-8");
            ow.write(_str);
            ow.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
